package com.example.cardgame

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class CardAdapter(private val context: Context, private val cards: List<Card>) : BaseAdapter() {

    override fun getCount(): Int = cards.size

    override fun getItem(position: Int): Any = cards[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val card = cards[position]
        val imageView: ImageView = if (convertView == null) {
            ImageView(context).apply {
                layoutParams = ViewGroup.LayoutParams(200, 300)
                scaleType = ImageView.ScaleType.CENTER_CROP
                // 设置卡牌样式背景
                setBackgroundResource(R.drawable.card_selector)
            }
        } else {
            convertView as ImageView
        }



        // 设置卡牌图像
        if (card.isFlipped) {
            // 如果牌被翻开，显示牌面
            imageView.setImageResource(getCardImage(card.id))
        } else {
            // 如果牌没有被翻开，显示背面
            imageView.setImageResource(R.drawable.default_avatar)
        }

        return imageView
    }

    // 根据卡牌 ID 返回对应的图像
    private fun getCardImage(cardId: Int): Int {
        return when (cardId) {
            1 -> R.drawable.grid_apple
            2 -> R.drawable.grid_grape
            3 -> R.drawable.grid_mango
            4 -> R.drawable.grid_peach
            5 -> R.drawable.grid_orange
            6 -> R.drawable.grid_strawberry
            else -> R.drawable.default_avatar
        }
    }
}
